from functools import cache
from rest_framework import generics

from core.permissions import IsAdminUser
from .models import AppInfo, Agreement, Banner, CustomerService, PlatformSettings, PrivacyPolicy, SMSTemplate
from .serializers import AppInfoSerializer, AgreementSerializer, BannerSerializer, CustomerServiceSerializer, PlatformSettingsSerializer, PrivacyPolicySerializer, SMSTemplateSerializer

class AppInfoView(generics.RetrieveAPIView):
    serializer_class = AppInfoSerializer
    
    def get_object(self):
        # 添加缓存机制
        cache_key = 'latest_app_info'
        cached = cache.get(cache_key)
        if cached:
            return cached
            
        obj = AppInfo.objects.latest('created_at')
        cache.set(cache_key, obj, timeout=60*60)  # 缓存1小时
        return obj

class AgreementView(generics.RetrieveAPIView):
    serializer_class = AgreementSerializer
    authentication_classes = []  # 无需认证
    permission_classes = []
    
    def get_object(self):
        return Agreement.objects.latest('effective_date')

class PrivacyPolicyView(generics.RetrieveAPIView):
    serializer_class = PrivacyPolicySerializer
    authentication_classes = []
    permission_classes = []
    
    def get_object(self):
        return PrivacyPolicy.objects.latest('effective_date')

#后台

# views.py (新增内容)
class BannerView(generics.ListCreateAPIView):
    queryset = Banner.objects.filter(is_active=True).order_by('display_order')
    serializer_class = BannerSerializer
    permission_classes = [IsAdminUser]

class BannerDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Banner.objects.all()
    serializer_class = BannerSerializer
    permission_classes = [IsAdminUser]

class PlatformSettingsView(generics.RetrieveUpdateAPIView):
    queryset = PlatformSettings.objects.all()
    serializer_class = PlatformSettingsSerializer
    permission_classes = [IsAdminUser]
    
    def get_object(self):
        obj, created = PlatformSettings.objects.get_or_create(pk=1)
        return obj

class SMSTemplateView(generics.ListAPIView):
    queryset = SMSTemplate.objects.filter(is_active=True)
    serializer_class = SMSTemplateSerializer
    permission_classes = [IsAdminUser]

class SMSTemplateDetailView(generics.RetrieveUpdateAPIView):
    queryset = SMSTemplate.objects.all()
    serializer_class = SMSTemplateSerializer
    permission_classes = [IsAdminUser]

class CustomerServiceView(generics.RetrieveUpdateAPIView):
    queryset = CustomerService.objects.all()
    serializer_class = CustomerServiceSerializer
    permission_classes = [IsAdminUser]
    
    def get_object(self):
        obj, created = CustomerService.objects.get_or_create(pk=1)
        return obj